import { onBeforeUnmount, onDeactivated, watch } from "vue"
import { onMountedOrActivated } from "./onMountedOrActivated"

let totalLockCount = 0

const BODY_LOCK_CLASS = 'op-overflow-hidden'
export function useLockScroll(shouldLock: () => boolean) {
  const lock = () => {
    if (!totalLockCount) {
      document.body.classList.add(BODY_LOCK_CLASS)
    }
    totalLockCount++
  }
  const unlock = () => {
    if (totalLockCount) {
      totalLockCount--
      if (!totalLockCount) {
        document.body.classList.remove(BODY_LOCK_CLASS)
      }
    }
  }

  onMountedOrActivated(() => {
    if (shouldLock()) {
      lock()
    }
  })
//在 onDeactivated 和 onBeforeUnmount 回调函数中，直接调用 unlock 函数，
// 确保在组件失活或卸载时，无论 shouldLock 的值如何，只要 totalLockCount 大于 0，就会移除滚动锁定类名
  const destroy = () => {
    if (shouldLock()) {
      unlock()
    }
  }

  onDeactivated(() => {
    destroy()
  })

  onBeforeUnmount(() => {
    destroy()
  })
//在 watch 监听回调函数中，比较 shouldLock 函数的新旧值（newValue 和 oldValue），只有当值发生变化时才执行 lock 或 unlock 操作
  watch(shouldLock, (newValue, oldValue) => {
    if (newValue &&!oldValue) {
      lock()
    } else if (!newValue && oldValue) {
      unlock()
    }
  })
}

